﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySqlCode.Model;

namespace MySqlCode
{
    public class App
    {
        public static List<DataInfo> Datas { get; set; }
        public static DataInfo Database { get; set; }

        public static void LodaData()
        {
            var rootPath = Directory.GetCurrentDirectory();
            var filePath = rootPath + "/data";
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
            }
            var txt = File.ReadAllLines(filePath);
            PushDatas(txt);
        }

        public static void PushDatas(string[] datas)
        {
            List<DataInfo> list = new List<DataInfo>();
            foreach (var item in datas)
            {
                var arr = Handler.Safety.Decryption(item).Split(new string[] { "|-|" }, StringSplitOptions.RemoveEmptyEntries);
                var model = new Model.DataInfo()
                {
                    GUID = arr[0],
                    Name = arr[1],
                    Host = arr[2],
                    Port = arr[3],
                    User = arr[4],
                    Pwd = arr[5]
                };
                list.Add(model);
            }
            Datas = list;
        }

        public static void Save()
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataInfo item in Datas)
            {
                string str = $"{item.GUID}|-|{item.Name}|-|{item.Host}|-|{item.Port}|-|{item.User}|-|{item.Pwd}";
                str = Handler.Safety.Encrypt(str);
                sb.AppendLine(str);
            }

            var rootPath = Directory.GetCurrentDirectory();
            var filePath = rootPath + "/data";
            File.WriteAllText(filePath, sb.ToString());
        }

        public static Model.DataInfo GetModel(string guid)
        {
            return Datas.First(x => x.GUID == guid);
        }

        public static void Delete(Model.DataInfo model)
        {
            Datas.Remove(model);
            Save();
        }

        public static void Update(Model.DataInfo model)
        {
            Datas.ForEach(x =>
            {
                if (x.GUID == model.GUID)
                {
                    x.Name = model.Name;
                    x.Host = model.Host;
                    x.Port = model.Port;
                    x.User = model.User;
                    x.Pwd = model.Pwd;
                }
            });
            Save();
        }

        public static void Insert(Model.DataInfo model)
        {
            Datas.Add(model);
            Save();
        }
    }
}
